﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Windows.Forms;
using FBroSharp;               // ⚠️ #1 CRITICAL! FBroSharpControl, FBroSharpBrowserListControl
using FBroSharp.Lib;          // IFBroSharpBrowser, IFBroSharpFrame
using FBroSharp.Value;        // FBroSharpWindowsInfo, FBroSharpBrowserSetting
using FBroSharp.DataType;     // FBroSharpEventDisableControl
using FBroSharp.Callback;     // FBroSharpCookieVisitor, FBroSharpSynHelp
using Newtonsoft.Json;        // JSON序列化

namespace Cookie管理浏览器
{
    public partial class Form1 : Form
    {
        private const string BROWSER_USER_FLAG = "cookie_manager_browser";
        private Dictionary<string, string> _accountCookies = new Dictionary<string, string>();
        private string _accountStorePath = Path.Combine(Environment.CurrentDirectory, "Accounts");

        public Form1()
        {
            InitializeComponent();
            
            // 创建账户存储目录
            if (!Directory.Exists(_accountStorePath))
            {
                Directory.CreateDirectory(_accountStorePath);
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            try
            {
                CreateBrowser();
                LoadAccounts();
            }
            catch (Exception ex)
            {
                MessageBox.Show($"浏览器创建失败: {ex.Message}", "错误", 
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        #region 浏览器创建和管理

        private void CreateBrowser()
        {
            // ⚠️ CRITICAL: 使用正确的类型名称
            FBroSharpWindowsInfo windowInfo = new FBroSharpWindowsInfo
            {
                parent_window = panelBrowser.Handle,  // 嵌入到Panel中
                x = 0,
                y = 0,
                width = panelBrowser.Width,
                height = panelBrowser.Height,
                window_name = "Cookie管理浏览器"
            };

            FBroSharpBrowserSetting settings = new FBroSharpBrowserSetting();

            BrowserEvent browserEvent = new BrowserEvent(this);

            // ⚠️ CRITICAL: event_control 使用 default，不是 null！
            bool success = FBroSharpControl.CreatBrowser(
                txtUrl.Text,
                windowInfo,
                settings,
                null,  // request_context
                null,  // extra_info
                browserEvent,
                default,  // ✅ 使用 default for struct value type
                BROWSER_USER_FLAG
            );

            if (!success)
            {
                MessageBox.Show("浏览器创建失败！", "错误", 
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void Form1_Resize(object sender, EventArgs e)
        {
            ResizeEmbeddedBrowser();
        }

        private void ResizeEmbeddedBrowser()
        {
            try
            {
                var browser = FBroSharpBrowserListControl.GetBrowserFromFlag(BROWSER_USER_FLAG);
                if (browser != null && browser.IsValid)
                {
                    browser.MoveWindow(0, 0, panelBrowser.Width, panelBrowser.Height, true);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"调整浏览器大小失败: {ex.Message}");
            }
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            try
            {
                var browser = FBroSharpBrowserListControl.GetBrowserFromFlag(BROWSER_USER_FLAG);
                if (browser != null && browser.IsValid)
                {
                    browser.CloseBrowser(false, false);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"关闭浏览器失败: {ex.Message}");
            }
        }

        #endregion

        #region 导航功能

        private void btnGo_Click(object sender, EventArgs e)
        {
            NavigateToUrl(txtUrl.Text);
        }

        private void btnBack_Click(object sender, EventArgs e)
        {
            try
            {
                var browser = FBroSharpBrowserListControl.GetBrowserFromFlag(BROWSER_USER_FLAG);
                if (browser != null && browser.IsValid)
                {
                    browser.GoBack();
                }
            }
            catch (Exception ex)
            {
                UpdateStatus($"后退失败: {ex.Message}");
            }
        }

        private void btnForward_Click(object sender, EventArgs e)
        {
            try
            {
                var browser = FBroSharpBrowserListControl.GetBrowserFromFlag(BROWSER_USER_FLAG);
                if (browser != null && browser.IsValid)
                {
                    browser.GoForward();
                }
            }
            catch (Exception ex)
            {
                UpdateStatus($"前进失败: {ex.Message}");
            }
        }

        private void btnRefresh_Click(object sender, EventArgs e)
        {
            try
            {
                var browser = FBroSharpBrowserListControl.GetBrowserFromFlag(BROWSER_USER_FLAG);
                if (browser != null && browser.IsValid)
                {
                    browser.Reload();
                }
            }
            catch (Exception ex)
            {
                UpdateStatus($"刷新失败: {ex.Message}");
            }
        }

        private void NavigateToUrl(string url)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(url))
                {
                    MessageBox.Show("请输入URL", "提示", 
                        MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }

                if (!url.StartsWith("http://") && !url.StartsWith("https://"))
                {
                    url = "https://" + url;
                }

                var browser = FBroSharpBrowserListControl.GetBrowserFromFlag(BROWSER_USER_FLAG);
                if (browser != null && browser.IsValid)
                {
                    var frame = browser.GetMainFrame();
                    if (frame != null && frame.IsValid)
                    {
                        frame.LoadURL(url);
                        UpdateStatus($"正在访问: {url}");
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"导航失败: {ex.Message}", "错误", 
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        #endregion

        #region Cookie管理

        private void btnRefreshCookies_Click(object sender, EventArgs e)
        {
            RefreshCookies();
        }

        private void RefreshCookies()
        {
            try
            {
                var browser = FBroSharpBrowserListControl.GetBrowserFromFlag(BROWSER_USER_FLAG);
                if (browser == null || !browser.IsValid)
                {
                    UpdateStatus("浏览器未就绪");
                    return;
                }

                string url = txtUrl.Text;
                if (string.IsNullOrWhiteSpace(url))
                {
                    url = "https://www.baidu.com";
                }

                // ⚠️ CRITICAL: 使用完整的 FBroSharpCookieVisitor 实现
                var visitor = new JsonCookieCollectorVisitor();
                var cookieManager = browser.GetRequestContext().GetCookieManager();
                
                cookieManager.VisitUrlCookies(url, true, visitor);

                // ⚠️ CRITICAL: 必须等待异步操作完成
                if (visitor.Help != null && visitor.Help.IsValid)
                {
                    visitor.Help.WaitEvent(10 * 1000);  // 等待最多10秒

                    if (visitor.Help.HavStringData())
                    {
                        string jsonResult = visitor.Help.GetStringData();
                        visitor.Help.ClearData();

                        DisplayCookies(jsonResult);
                        UpdateStatus($"Cookie获取成功，共 {visitor.CookieCount} 个");
                    }
                    else
                    {
                        UpdateStatus("未获取到Cookie数据");
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"获取Cookie失败: {ex.Message}", "错误", 
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void DisplayCookies(string jsonCookies)
        {
            if (InvokeRequired)
            {
                Invoke(new Action<string>(DisplayCookies), jsonCookies);
                return;
            }

            try
            {
                listViewCookies.Items.Clear();

                var cookies = JsonConvert.DeserializeObject<List<CookieData>>(jsonCookies);
                if (cookies != null)
                {
                    foreach (var cookie in cookies)
                    {
                        var item = new ListViewItem(cookie.name);
                        item.SubItems.Add(cookie.value);
                        item.SubItems.Add(cookie.domain);
                        item.SubItems.Add(cookie.path);
                        item.SubItems.Add(cookie.expires);
                        item.Tag = cookie;
                        listViewCookies.Items.Add(item);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"显示Cookie失败: {ex.Message}", "错误", 
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnEditCookie_Click(object sender, EventArgs e)
        {
            if (listViewCookies.SelectedItems.Count == 0)
            {
                MessageBox.Show("请先选择要编辑的Cookie", "提示", 
                    MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            var selectedCookie = listViewCookies.SelectedItems[0].Tag as CookieData;
            if (selectedCookie != null)
            {
                using (var editForm = new CookieEditForm(selectedCookie))
                {
                    if (editForm.ShowDialog() == DialogResult.OK)
                    {
                        SetCookie(editForm.EditedCookie);
                        RefreshCookies();
                    }
                }
            }
        }

        private void btnDeleteCookie_Click(object sender, EventArgs e)
        {
            if (listViewCookies.SelectedItems.Count == 0)
            {
                MessageBox.Show("请先选择要删除的Cookie", "提示", 
                    MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            var selectedCookie = listViewCookies.SelectedItems[0].Tag as CookieData;
            if (selectedCookie != null)
            {
                if (MessageBox.Show($"确定要删除Cookie '{selectedCookie.name}' 吗？", 
                    "确认删除", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    DeleteCookie(selectedCookie);
                    RefreshCookies();
                }
            }
        }

        private void btnDeleteAllCookies_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("确定要清空所有Cookie吗？", "确认清空", 
                MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
            {
                try
                {
                    var browser = FBroSharpBrowserListControl.GetBrowserFromFlag(BROWSER_USER_FLAG);
                    if (browser != null && browser.IsValid)
                    {
                        var cookieManager = browser.GetRequestContext().GetCookieManager();
                        cookieManager.DeleteCookies("", "");
                        
                        listViewCookies.Items.Clear();
                        UpdateStatus("所有Cookie已清空");
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"清空Cookie失败: {ex.Message}", "错误", 
                        MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }

        private void SetCookie(CookieData cookie)
        {
            try
            {
                var browser = FBroSharpBrowserListControl.GetBrowserFromFlag(BROWSER_USER_FLAG);
                if (browser != null && browser.IsValid)
                {
                    var cookieManager = browser.GetRequestContext().GetCookieManager();
                    
                    string url = $"https://{cookie.domain.TrimStart('.')}{cookie.path}";
                    
                    // 创建FBroSharpCookieData结构体
                    FBroSharpCookieData cookieData = new FBroSharpCookieData
                    {
                        name = cookie.name,
                        value = cookie.value,
                        domain = cookie.domain,
                        path = cookie.path,
                        httponly = cookie.httponly,
                        has_expires = true,
                        expires_time = DateTime.Now.AddYears(1),
                        last_access_time = DateTime.Now,
                        secure = cookie.secure ? 1 : 0,  // bool转int
                        same_site = 0,  // 0 = NO_RESTRICTION
                        priority = 0
                    };
                    
                    cookieManager.SetCookie(url, cookieData);
                    
                    UpdateStatus($"Cookie '{cookie.name}' 已更新");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"设置Cookie失败: {ex.Message}", "错误", 
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void DeleteCookie(CookieData cookie)
        {
            try
            {
                var browser = FBroSharpBrowserListControl.GetBrowserFromFlag(BROWSER_USER_FLAG);
                if (browser != null && browser.IsValid)
                {
                    var cookieManager = browser.GetRequestContext().GetCookieManager();
                    string url = $"https://{cookie.domain.TrimStart('.')}{cookie.path}";
                    
                    cookieManager.DeleteCookies(url, cookie.name);
                    UpdateStatus($"Cookie '{cookie.name}' 已删除");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"删除Cookie失败: {ex.Message}", "错误", 
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnImportCookies_Click(object sender, EventArgs e)
        {
            try
            {
                using (OpenFileDialog ofd = new OpenFileDialog())
                {
                    ofd.Filter = "JSON文件 (*.json)|*.json|所有文件 (*.*)|*.*";
                    ofd.Title = "导入Cookie";

                    if (ofd.ShowDialog() == DialogResult.OK)
                    {
                        string jsonContent = File.ReadAllText(ofd.FileName, Encoding.UTF8);
                        var cookies = JsonConvert.DeserializeObject<List<CookieData>>(jsonContent);

                        if (cookies != null && cookies.Count > 0)
                        {
                            foreach (var cookie in cookies)
                            {
                                SetCookie(cookie);
                            }

                            RefreshCookies();
                            MessageBox.Show($"成功导入 {cookies.Count} 个Cookie", "导入成功", 
                                MessageBoxButtons.OK, MessageBoxIcon.Information);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"导入Cookie失败: {ex.Message}", "错误", 
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnExportCookies_Click(object sender, EventArgs e)
        {
            try
            {
                var browser = FBroSharpBrowserListControl.GetBrowserFromFlag(BROWSER_USER_FLAG);
                if (browser == null || !browser.IsValid)
                {
                    MessageBox.Show("浏览器未就绪", "提示", 
                        MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }

                string url = txtUrl.Text;
                if (string.IsNullOrWhiteSpace(url))
                {
                    url = "https://www.baidu.com";
                }

                var visitor = new JsonCookieCollectorVisitor();
                var cookieManager = browser.GetRequestContext().GetCookieManager();
                
                cookieManager.VisitUrlCookies(url, true, visitor);

                if (visitor.Help != null && visitor.Help.IsValid)
                {
                    visitor.Help.WaitEvent(10 * 1000);

                    if (visitor.Help.HavStringData())
                    {
                        string jsonResult = visitor.Help.GetStringData();
                        visitor.Help.ClearData();

                        using (SaveFileDialog sfd = new SaveFileDialog())
                        {
                            sfd.Filter = "JSON文件 (*.json)|*.json|所有文件 (*.*)|*.*";
                            sfd.Title = "导出Cookie";
                            sfd.FileName = $"cookies_{DateTime.Now:yyyyMMdd_HHmmss}.json";

                            if (sfd.ShowDialog() == DialogResult.OK)
                            {
                                File.WriteAllText(sfd.FileName, jsonResult, Encoding.UTF8);
                                MessageBox.Show($"Cookie已导出到: {sfd.FileName}", "导出成功", 
                                    MessageBoxButtons.OK, MessageBoxIcon.Information);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"导出Cookie失败: {ex.Message}", "错误", 
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        #endregion

        #region 账户管理

        private void LoadAccounts()
        {
            try
            {
                listBoxAccounts.Items.Clear();
                _accountCookies.Clear();

                if (Directory.Exists(_accountStorePath))
                {
                    foreach (var file in Directory.GetFiles(_accountStorePath, "*.json"))
                    {
                        string accountName = Path.GetFileNameWithoutExtension(file);
                        string cookieData = File.ReadAllText(file, Encoding.UTF8);
                        
                        _accountCookies[accountName] = cookieData;
                        listBoxAccounts.Items.Add(accountName);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载账户失败: {ex.Message}", "错误", 
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnSaveAccount_Click(object sender, EventArgs e)
        {
            try
            {
                string accountName = txtAccountName.Text.Trim();
                if (string.IsNullOrWhiteSpace(accountName))
                {
                    MessageBox.Show("请输入账户名称", "提示", 
                        MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }

                var browser = FBroSharpBrowserListControl.GetBrowserFromFlag(BROWSER_USER_FLAG);
                if (browser == null || !browser.IsValid)
                {
                    MessageBox.Show("浏览器未就绪", "提示", 
                        MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }

                string url = txtUrl.Text;
                if (string.IsNullOrWhiteSpace(url))
                {
                    url = "https://www.baidu.com";
                }

                var visitor = new JsonCookieCollectorVisitor();
                var cookieManager = browser.GetRequestContext().GetCookieManager();
                
                cookieManager.VisitUrlCookies(url, true, visitor);

                if (visitor.Help != null && visitor.Help.IsValid)
                {
                    visitor.Help.WaitEvent(10 * 1000);

                    if (visitor.Help.HavStringData())
                    {
                        string jsonResult = visitor.Help.GetStringData();
                        visitor.Help.ClearData();

                        string filePath = Path.Combine(_accountStorePath, $"{accountName}.json");
                        File.WriteAllText(filePath, jsonResult, Encoding.UTF8);

                        _accountCookies[accountName] = jsonResult;
                        
                        if (!listBoxAccounts.Items.Contains(accountName))
                        {
                            listBoxAccounts.Items.Add(accountName);
                        }

                        MessageBox.Show($"账户 '{accountName}' 已保存", "保存成功", 
                            MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"保存账户失败: {ex.Message}", "错误", 
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnSwitchAccount_Click(object sender, EventArgs e)
        {
            if (listBoxAccounts.SelectedItem == null)
            {
                MessageBox.Show("请先选择要切换的账户", "提示", 
                    MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            try
            {
                string accountName = listBoxAccounts.SelectedItem.ToString();
                
                if (!_accountCookies.ContainsKey(accountName))
                {
                    MessageBox.Show("账户数据不存在", "错误", 
                        MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                // 先清空当前Cookie
                var browser = FBroSharpBrowserListControl.GetBrowserFromFlag(BROWSER_USER_FLAG);
                if (browser != null && browser.IsValid)
                {
                    var cookieManager = browser.GetRequestContext().GetCookieManager();
                    cookieManager.DeleteCookies("", "");

                    // 导入账户Cookie
                    string jsonCookies = _accountCookies[accountName];
                    var cookies = JsonConvert.DeserializeObject<List<CookieData>>(jsonCookies);

                    if (cookies != null && cookies.Count > 0)
                    {
                        foreach (var cookie in cookies)
                        {
                            SetCookie(cookie);
                        }

                        RefreshCookies();
                        MessageBox.Show($"已切换到账户 '{accountName}'", "切换成功", 
                            MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"切换账户失败: {ex.Message}", "错误", 
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnDeleteAccount_Click(object sender, EventArgs e)
        {
            if (listBoxAccounts.SelectedItem == null)
            {
                MessageBox.Show("请先选择要删除的账户", "提示", 
                    MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            string accountName = listBoxAccounts.SelectedItem.ToString();

            if (MessageBox.Show($"确定要删除账户 '{accountName}' 吗？", "确认删除", 
                MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                try
                {
                    string filePath = Path.Combine(_accountStorePath, $"{accountName}.json");
                    if (File.Exists(filePath))
                    {
                        File.Delete(filePath);
                    }

                    _accountCookies.Remove(accountName);
                    listBoxAccounts.Items.Remove(accountName);

                    MessageBox.Show($"账户 '{accountName}' 已删除", "删除成功", 
                        MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"删除账户失败: {ex.Message}", "错误", 
                        MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }

        #endregion

        #region UI更新方法（从BrowserEvent调用）

        public void UpdateStatus(string message)
        {
            if (InvokeRequired)
            {
                Invoke(new Action<string>(UpdateStatus), message);
                return;
            }

            toolStripStatusLabel.Text = message;
        }

        public void UpdateUrl(string url)
        {
            if (InvokeRequired)
            {
                Invoke(new Action<string>(UpdateUrl), url);
                return;
            }

            txtUrl.Text = url;
        }

        public void UpdateTitle(string title)
        {
            if (InvokeRequired)
            {
                Invoke(new Action<string>(UpdateTitle), title);
                return;
            }

            this.Text = $"Cookie管理浏览器 - {title}";
        }

        public void UpdateLoadingState(bool isLoading)
        {
            if (InvokeRequired)
            {
                Invoke(new Action<bool>(UpdateLoadingState), isLoading);
                return;
            }

            if (isLoading)
            {
                UpdateStatus("加载中...");
            }
        }

        #endregion
    }

    #region Cookie访问器类 - 完整实现

    /// <summary>
    /// ⚠️ CRITICAL: 完整的Cookie访问器实现（带FBroSharpSynHelp）
    /// 这是Cookie管理的核心组件，必须完整实现！
    /// </summary>
    public class JsonCookieCollectorVisitor : FBroSharpCookieVisitor
    {
        public FBroSharpSynHelp Help { get; private set; }
        public int CookieCount { get; private set; }
        private List<object> cookieList;

        public JsonCookieCollectorVisitor()
        {
            Help = new FBroSharpSynHelp();
            cookieList = new List<object>();
            CookieCount = 0;
        }

        public override bool Visit(FBroSharpCookieData cookie, int count, int total, out bool deleteCookie)
        {
            var cookieJson = new
            {
                name = cookie.name,
                value = cookie.value,
                domain = cookie.domain,
                path = cookie.path,
                secure = cookie.secure == 1,  // int转bool
                httponly = cookie.httponly,
                expires = cookie.expires_time.ToString("yyyy-MM-dd HH:mm:ss")  // 使用expires_time
            };

            cookieList.Add(cookieJson);
            CookieCount++;
            deleteCookie = false;

            // ⚠️ CRITICAL: 必须在完成时调用StopEvent()
            if (count + 1 == total)
            {
                string finalJsonArray = JsonConvert.SerializeObject(cookieList, Formatting.Indented);
                Help.SetStringData(finalJsonArray);
                Help.StopEvent();  // ✅ 通知等待线程完成
            }

            return true;
        }
    }

    #endregion

    #region Cookie数据类

    public class CookieData
    {
        public string name { get; set; }
        public string value { get; set; }
        public string domain { get; set; }
        public string path { get; set; }
        public bool secure { get; set; }
        public bool httponly { get; set; }
        public string expires { get; set; }
    }

    #endregion

    #region Cookie编辑窗体

    public class CookieEditForm : Form
    {
        private TextBox txtName;
        private TextBox txtValue;
        private TextBox txtDomain;
        private TextBox txtPath;
        private CheckBox chkSecure;
        private CheckBox chkHttpOnly;
        private Button btnOK;
        private Button btnCancel;

        public CookieData EditedCookie { get; private set; }

        public CookieEditForm(CookieData cookie)
        {
            InitializeComponent();
            EditedCookie = new CookieData
            {
                name = cookie.name,
                value = cookie.value,
                domain = cookie.domain,
                path = cookie.path,
                secure = cookie.secure,
                httponly = cookie.httponly,
                expires = cookie.expires
            };

            txtName.Text = cookie.name;
            txtValue.Text = cookie.value;
            txtDomain.Text = cookie.domain;
            txtPath.Text = cookie.path;
            chkSecure.Checked = cookie.secure;
            chkHttpOnly.Checked = cookie.httponly;
        }

        private void InitializeComponent()
        {
            this.txtName = new TextBox();
            this.txtValue = new TextBox();
            this.txtDomain = new TextBox();
            this.txtPath = new TextBox();
            this.chkSecure = new CheckBox();
            this.chkHttpOnly = new CheckBox();
            this.btnOK = new Button();
            this.btnCancel = new Button();

            this.SuspendLayout();

            // txtName
            this.txtName.Location = new System.Drawing.Point(100, 20);
            this.txtName.Size = new System.Drawing.Size(280, 21);

            // txtValue
            this.txtValue.Location = new System.Drawing.Point(100, 50);
            this.txtValue.Size = new System.Drawing.Size(280, 21);

            // txtDomain
            this.txtDomain.Location = new System.Drawing.Point(100, 80);
            this.txtDomain.Size = new System.Drawing.Size(280, 21);

            // txtPath
            this.txtPath.Location = new System.Drawing.Point(100, 110);
            this.txtPath.Size = new System.Drawing.Size(280, 21);

            // chkSecure
            this.chkSecure.Location = new System.Drawing.Point(100, 140);
            this.chkSecure.Text = "Secure";
            this.chkSecure.Size = new System.Drawing.Size(120, 24);

            // chkHttpOnly
            this.chkHttpOnly.Location = new System.Drawing.Point(220, 140);
            this.chkHttpOnly.Text = "HttpOnly";
            this.chkHttpOnly.Size = new System.Drawing.Size(120, 24);

            // btnOK
            this.btnOK.Location = new System.Drawing.Point(220, 180);
            this.btnOK.Size = new System.Drawing.Size(75, 23);
            this.btnOK.Text = "确定";
            this.btnOK.DialogResult = DialogResult.OK;
            this.btnOK.Click += (s, e) =>
            {
                EditedCookie.name = txtName.Text;
                EditedCookie.value = txtValue.Text;
                EditedCookie.domain = txtDomain.Text;
                EditedCookie.path = txtPath.Text;
                EditedCookie.secure = chkSecure.Checked;
                EditedCookie.httponly = chkHttpOnly.Checked;
            };

            // btnCancel
            this.btnCancel.Location = new System.Drawing.Point(305, 180);
            this.btnCancel.Size = new System.Drawing.Size(75, 23);
            this.btnCancel.Text = "取消";
            this.btnCancel.DialogResult = DialogResult.Cancel;

            // Labels
            Label lblName = new Label { Text = "名称:", Location = new System.Drawing.Point(20, 23), Size = new System.Drawing.Size(70, 15) };
            Label lblValue = new Label { Text = "值:", Location = new System.Drawing.Point(20, 53), Size = new System.Drawing.Size(70, 15) };
            Label lblDomain = new Label { Text = "域:", Location = new System.Drawing.Point(20, 83), Size = new System.Drawing.Size(70, 15) };
            Label lblPath = new Label { Text = "路径:", Location = new System.Drawing.Point(20, 113), Size = new System.Drawing.Size(70, 15) };

            // Form
            this.Controls.Add(lblName);
            this.Controls.Add(txtName);
            this.Controls.Add(lblValue);
            this.Controls.Add(txtValue);
            this.Controls.Add(lblDomain);
            this.Controls.Add(txtDomain);
            this.Controls.Add(lblPath);
            this.Controls.Add(txtPath);
            this.Controls.Add(chkSecure);
            this.Controls.Add(chkHttpOnly);
            this.Controls.Add(btnOK);
            this.Controls.Add(btnCancel);

            this.ClientSize = new System.Drawing.Size(400, 220);
            this.Text = "编辑Cookie";
            this.StartPosition = FormStartPosition.CenterParent;
            this.FormBorderStyle = FormBorderStyle.FixedDialog;
            this.MaximizeBox = false;
            this.MinimizeBox = false;
            this.AcceptButton = btnOK;
            this.CancelButton = btnCancel;

            this.ResumeLayout(false);
        }
    }

    #endregion
}
